package com.example.community.controller;

import com.example.community.entity.DiscussPost;
import com.example.community.entity.Page;
import com.example.community.service.ElasticsearchService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;
import com.example.community.util.CommunityConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;


    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model){
        log.info("keyword {}",keyword);
        log.info("page {}",page);
        log.info("model {}",model);
        // 搜索帖子 包含总记录数 和 每页数据
        Map<String, Object> postMap = elasticsearchService.searchDiscussPost(
                keyword, page.getCurrent() - 1, page.getLimit());

        long count = (long) postMap.get("count");   // 总记录数
        List<DiscussPost> posts = (List<DiscussPost>) postMap.get("discussPosts");  // 当前页的帖子数据

        // 分页信息
        page.setPath("/search?keyword=" + keyword);
        page.setRows((int)count);

        // 聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if(posts != null){
            for(DiscussPost post :posts){
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user", userService.findUserById(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLIkeCount(ENTITY_TYPE_POST,  post.getId()));

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);   // 帖子详情数据
        model.addAttribute("keyword", keyword);             // 关键字

        return "site/search";


    }


}
